Skip to content

ajax fetch axios 区别,ajax 实现原理, axios 原理是什么

ajax

  • new XMLHttpRequest()
  • onreadystatechange
  • readyState == 4
  • state == 200 304
  • xhr.reponseText;
js
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActiveXObject('Microsoft.XMLHTTP')
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200 || xhr.status == 304) {
      var obj = {
        text: xhr.responseText,
        json: JSON.parse(xhr.responseText),
      };
      var data = obj[dataType];
      if(typeof c.success === "function") {
        c.success(data);
      }
  }   
}
js
function ajax(opt) {
  var xhr = XMLHttpRequest ? new XMLHttpRequest() : new window.ActivedXObject('Microsoft.XMLHTTP')
  var data = opt.data,
  url = opt.url,
  type = opt.type.toUpperCase(),
  dataArr = []
  for(k in data) {
    dataArr.push(k + '=' + data[k])
  }
  if (type === 'GET') {
    url = url + '?' + dataArr.join('&')
    xhr.open(type, url.replace(/\?&/g, ''), true)
    xhr.send()
  } else if (type === 'POST') {
    xhr.open(type, url, true)
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
    xhr.send(dataArr.join('&'))
  }
  xhr.onload = function() {
    if (xhr.status === 200 || xhr.status === 304) {
      var res;
      if (opt.success || opt.success instanceof Function) {
        res = xhr.responseText;
        if (typeof res === 'string') {
          res = JSON.parse(res)
          opt.success.call(xhr,res)
        }
      }
    } else {
      if (opt.error || opt.error instanceof Function) {
          opt.error.call(xhr,res)
      }
    }
  }
}

fetch

ES6出现的, 使用了es6 promise 对象,fetch 不是 ajax 的进一步封装,而是原生js,没有使用 XMLHttpRequest 对象 优:解决回调地狱,简洁 缺:默认不带 cookie,浏览支持不很好,需要 ployfill, 不支持 abort 超时处理

用 fetch 封装最大并发请求函数

js

axios

底层还是对ajax 封装,需要一个promise 返回结果

支持 promise 异步请求 拦截请求 取消请求 并发请求 超时时间设置

在 MIT 许可下发布